package com.smallyang.job;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.smallyang.constants.RedisConstants;
import com.smallyang.domain.entity.Article;
import com.smallyang.mapper.ArticleMapper;
import com.smallyang.service.ArticleService;
import com.smallyang.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 杨森
 * @description:
 * @date 2023年05月20日 10:49
 */
@Component
public class UpdateViewCountJob {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleService articleService;
    @Autowired
    ArticleMapper articleMapper ;
    //每过一分钟从redis中更新浏览量到数据库中
//    @Scheduled(cron = "* 0/1 * * * ?")
    @Scheduled(cron = "0/10 * * * * ?")
    public void UpdateViewCountJob(){
        //定时任务要执行的代码
        //获取redis中的浏览量

        Map<String, Integer> viewCounteMap = redisCache.getCacheMap(RedisConstants.ARTICLE_VIEWCOUNT_KEY);
        List<Article> articles = viewCounteMap.entrySet()
                .stream()
                .map(entry -> new Article(Long.valueOf(entry.getKey()), entry.getValue().longValue()))
                .collect(Collectors.toList());

        //更新到数据库中
        //articleService.updateBatchById(articles);
        for(int i = 0; i < articles.size(); i++){
            articleMapper.updateByIDD(articles.get(i).getViewCount(),articles.get(i).getId());
        }

    }
}
